  <template>
    <div style="background-color: lightgrey;height: 100%;width: 100%;overflow-y: auto;">
      <div id="head">
        <van-nav-bar  left-text="返回" left-arrow @click-left="onClickLeft" />
      </div>
    </div>
    <div class="header">登录</div>
    <van-form :modol="form" @submit="onSubmit" @failed="onFailed" ref="ruleFormRef">
      <div>
        <div>&nbsp;</div>
        <img class="tar" src="" alt="">
      </div>
      <van-field
        left-icon="friends-o"
        v-model="form.username"
        style="margin-top:10px"
        name="username"
        label="用户:"
        placeholder="请输入用户名"
        :rules="usernameRules"
        label-width="50"
        class="input" />

        <van-field
          left-icon="smile-comment-o"
          v-model="form.password"
          type="password"
          name="password"
          label="密码"
          placeholder="请输入密码"
          label-width="50"
          :rules="passwordRules"
          class="input" />

          <div style="margin: 16px;">
            <van-button round block type="info" native-type="submit" >登录</van-button>
            <div @click="toRegister" style="font-size: small;">没有账号？立即注册</div>
          </div>
    </van-form>
  </template>

  <style scoped>
    .input {
      margin-top: 50px;
      border-bottom: 1px solid #e2e2ee;
    }

    .header {
    font-size: 38px;
    font-weight: bold;
    text-align: center;
    line-height: 200px;
}
  </style>

<script setup>
import { reactive, ref } from 'vue';
import { useRouter } from 'vue-router';
import  useToken  from '../store/token';
import { login } from '../api/jiekou';
const router = useRouter()
const {updateToken} = useToken()

const form = reactive({
  username:'demo1',
  password:'123456'
})
const ruleFormRef = ref()

//定义验证规则
const usernameRules = ref([
  {required: true,message:'用户名不能为空'},
  {pattern:/^\w{3,16}$/,message:'用户名长度为3至16个字符'}
])
const passwordRules = ref ([
  {required:true,message:'密码不能为空'},
  {pattern:/^\w{3,16}$/,message:'密码必须为6到24为的英文字母或数字'}
])
//提交表单函数
const onSubmit = async values => {
  console.log(values);
  const data = await login(values)
  if (data) {
    updateToken(data.token)
    router.push({path:'/my'})
  }

}
const onFailed = errorInfo => {
  console.log('failed',errorInfo);
  
}
 const onClickLeft = () => history.back()
 const toRegister = () => {
    router.push({
      path:'/register'
    })
 }


</script>

